<!DOCTYPE html>
<html lang="en">

	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<title>Document</title>
		<style>
			#dvi {
            width: 800px;
            height: 600px;
            background: #ccc;
            position: absolute;
            top: 100px;
            left: 100px;
        }
    </style>
	</head>

	<body>
		<input type="button" value="弹出球" id="btn">
		<div id="dvi"></div>
		<script>
			var colors = ["#33B5E5", "#0099CC", "#AA66CC", "#9933CC", "#99CC00", "#669900", "#FFBB33", "#FF8800", "#FF4444",
				"#CC0000"
			];
			var dvi = document.getElementById('dvi');
			document.getElementById('btn').onclick = function() {
				//创建小球
				var box = document.createElement('div');
				box.style.cssText = "position: absolute;border-radius: 50%;";
				var br = Math.floor(Math.random() * 50) + 30;
				box.style.width = br + "px";
				box.style.height = br + "px";
				box.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
				dvi.appendChild(box);
				//获取小球对于div的中间位置
				var bx = (dvi.offsetWidth / 2) - (box.offsetWidth / 2);
				var by = (dvi.offsetHeight / 2) - (box.offsetHeight / 2);
				box.style.top = by + "px";
				box.style.left = bx + "px";
				var x = Math.floor(Math.random() * 10) + 1;
				var y = Math.floor(Math.random() * 10) + 1;
				var maxy = dvi.offsetHeight - box.offsetHeight;
				var maxw = dvi.offsetWidth - box.offsetWidth;
				setInterval(function() {
					bx += x;
					by += y;
					if (by > maxy || by < 0) {
						y = -y;
					}
					if (bx > maxw || bx < 0) {
						x = -x;
					}
					box.style.top = by + "px";
					box.style.left = bx + "px";
				}, 30)


			}
		</script>
	</body>

</html>
